﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace WorldClock.BO
{
    public class WorldTimeViewModel
    {
        private ObservableCollection<TimeZoneInfoViewModel> _timeZoneInfoViewModels;
        private DispatcherTimer _timeUpdaterTimer;
        public ObservableCollection<TimeZoneInfoViewModel> TimeZoneInfoViewModels 
        {
            get
            { return _timeZoneInfoViewModels; }
        }

        public WorldTimeViewModel()
        {
            _timeZoneInfoViewModels = new ObservableCollection<TimeZoneInfoViewModel>();
            ReadOnlyCollection<TimeZoneInfo> timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();
            foreach (TimeZoneInfo timeZoneInfo in timeZoneInfos)
            {
                _timeZoneInfoViewModels.Add(new TimeZoneInfoViewModel(timeZoneInfo));
            }                       
        }

        public void Init()
        {
            _timeUpdaterTimer = new DispatcherTimer();
            _timeUpdaterTimer.Interval = new TimeSpan(0, 0, 1);
            _timeUpdaterTimer.Tick += new EventHandler(TimeUpdaterTimer_Tick);
            _timeUpdaterTimer.Start(); 
        }

        public void Stop()
        {
            _timeUpdaterTimer.Stop(); 
            _timeUpdaterTimer.Tick -= new EventHandler(TimeUpdaterTimer_Tick);
            _timeUpdaterTimer = null;            
        }

        void TimeUpdaterTimer_Tick(object sender, EventArgs e)
        {
            foreach (TimeZoneInfoViewModel tzivm in _timeZoneInfoViewModels)
            {
                tzivm.RaiseTimeChanged();
            }
        }
    }
}
